package avl.sv.client;

import avl.sv.server.training.Training;
import avl.sv.shared.Permissions;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.Timer;

/**
 *
 * @author benbryan
 */
public class PermissionPrompt extends javax.swing.JDialog {

    private final Training trainingPort;
    private final String groupName;
    private final int objID;
    private final DefaultListModel<String> userListModel;
        
    public PermissionPrompt(    java.awt.Frame parent, 
                                        String groupName,
                                        int objID,
                                        Training trainingPort) {
        super(parent, true);
        initComponents();
        this.trainingPort = trainingPort;
        this.groupName = groupName; 
        this.objID = objID;
        
        // Populate comboboxes with Permissions
        jComboBoxPermissionsCurrentUser.removeAllItems();
        jComboBoxPermissionsNewUser.removeAllItems();
        for (final Permissions p:Permissions.values()){
            jComboBoxPermissionsCurrentUser.addItem(p);
            if (!p.equals(Permissions.DENIED)){
                jComboBoxPermissionsNewUser.addItem(p);
            }
        }

        
        userListModel = new DefaultListModel<>();
        String userList;
        switch (groupName) {
            case "solution":
                userList = trainingPort.getUsersInSolution(objID);
                break;
            case "study":
                userList = trainingPort.getUsersInStudy(objID);
                break;
            default:
                return;
        }
        
        
        if (!userList.isEmpty()){
            for (String username:userList.split(";")){
                userListModel.addElement(username);
            }
        }
        jListUsers.setModel(userListModel);
        jComboBoxPermissionsCurrentUser.addActionListener(jComboBoxPermissionsCurrentUserActionListener);
        setTitle("Managing permissions for " + groupName);
        pack();
    }
    
    DisableableActionListener jComboBoxPermissionsCurrentUserActionListener = new DisableableActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            if (enabled){
                String username = jListUsers.getSelectedValue();
                Permissions permission = (Permissions) jComboBoxPermissionsCurrentUser.getSelectedItem();
                changePermission(username, permission);
            }
        }
    };
    
    abstract private class DisableableActionListener implements ActionListener {
        protected boolean enabled = true;
        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }        
    };
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBoxPermissionsCurrentUser = new javax.swing.JComboBox<Permissions>();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListUsers = new javax.swing.JList<String>();
        jLabel3 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jButtonAddUser = new javax.swing.JButton();
        jTextFieldUsername = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxPermissionsNewUser = new javax.swing.JComboBox<Permissions>();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldNotification = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setLocationByPlatform(true);

        jLabel2.setText("Permission for select user");

        jListUsers.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListUsers.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListUsersValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jListUsers);

        jLabel3.setText("Current users");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Add user"));

        jButtonAddUser.setText("Add User");
        jButtonAddUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddUserActionPerformed(evt);
            }
        });

        jLabel1.setText("Username");

        jLabel4.setText("Permission");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonAddUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jComboBoxPermissionsNewUser, javax.swing.GroupLayout.Alignment.LEADING, 0, 97, Short.MAX_VALUE)
                            .addComponent(jTextFieldUsername, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(7, 7, 7)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxPermissionsNewUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonAddUser)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jComboBoxPermissionsCurrentUser, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jTextFieldNotification)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBoxPermissionsCurrentUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTextFieldNotification, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAddUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddUserActionPerformed
        String username = jTextFieldUsername.getText();
        Permissions permission = (Permissions) jComboBoxPermissionsNewUser.getSelectedItem();
        changePermission(username, permission);
    }//GEN-LAST:event_jButtonAddUserActionPerformed

    private Timer notificationClearTimer = new Timer(1000, new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
             jTextFieldNotification.setText("");
             notificationClearTimer.stop();
         }
     });
    
    private void setNotifications(String message){
        jTextFieldNotification.setText(message);
        notificationClearTimer.restart();
    }
    
    private void changePermission(String username, Permissions permission){
        String result;
        switch (groupName) {
            case "solution":
                result = trainingPort.setPermissionsSolution( objID, username, permission.name());
                break;
            case "study":
                result = trainingPort.setPermissionsStudy( objID, username, permission.name());
                break;
            default:
                return;
        }
        setNotifications(result);
        
        int userListModelNameIdx = -1;
        for (int i = 0; i < userListModel.size(); i++){
            if (username.equals(userListModel.get(i))){
                userListModelNameIdx = i;
                break;
            }
        }
        if (result.equals("Permission set")){
            if (permission == Permissions.DENIED){
                if (userListModelNameIdx >= 0 ){
                    // Delete the user from the list if permission denied
                    userListModel.remove(userListModelNameIdx);
                }
            } else { 
                if (userListModelNameIdx < 0) {
                    // Add the new user to the list
                    userListModel.addElement(username); 
                }
            }           
        }
    }
    
    private void jListUsersValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListUsersValueChanged
        if (evt.getValueIsAdjusting()){
            return;
        }
                
        String username  = jListUsers.getSelectedValue();
        if (username == null){
            return;
        }
        String permissionString;
        switch (groupName) {
            case "solution":
                permissionString = trainingPort.getPermissionsSolution(objID, username);
                break;
            case "study":
                permissionString = trainingPort.getPermissionsStudy(objID, username);
                break;
            default:
                return;
        }
        Permissions permissions = Permissions.valueOf(permissionString);
        jComboBoxPermissionsCurrentUserActionListener.setEnabled(false);
        jComboBoxPermissionsCurrentUser.setSelectedItem(permissions);
        jComboBoxPermissionsCurrentUserActionListener.setEnabled(true);
    }//GEN-LAST:event_jListUsersValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddUser;
    private javax.swing.JComboBox<Permissions> jComboBoxPermissionsCurrentUser;
    private javax.swing.JComboBox<Permissions> jComboBoxPermissionsNewUser;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JList<String> jListUsers;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextFieldNotification;
    private javax.swing.JTextField jTextFieldUsername;
    // End of variables declaration//GEN-END:variables
}
